import webview
import random
import json
from pathlib import Path
import re
import tkinter as tk
from tkinter import filedialog
import importlib
import os

from typing import  TypeVar,Union,Dict


class Api:
    def __init__(self,option:dict={}):
       pass 
       
    def log(self,*args):
        print(args)
    
    def __get_win(self):
        if not self.__win:
            self.__win = webview.windows[0]
        return self.__win

    def selectfile(self,mod):
        def open_dialog():
            global select_path 
            if mod == "file":
                select_path = filedialog.askopenfilename(parent=root,title="请选择",filetypes=[("chromedriver","*.exe")])
            else:
                select_path = filedialog.askdirectory(mustexist=False,parent=root,title="请选择目录")
           
            # self.__get_win().evaluate_js(f"window.path ='{select_path}'")
            root.destroy()
        
        # 创建一个主窗口
        root = tk.Tk()
        root.withdraw()
        root.after(1,open_dialog())
        root.mainloop()
        return select_path


    def get_drive_list(self):
        """获取电脑上的所有盘符列表"""
        drive_list = []
        for drive in range(ord('A'), ord('Z')+1):
            drive_name = chr(drive) + ':/'
            if os.path.exists(drive_name):
                drive_list.append(drive_name[:-1])
        return drive_list

    def _conmonfilter(self,fname:str):
        return fname[0] != '.' and fname[0] != '$'
    
    def listdir(self,root:str=None,model:str=None):
        if root is None or len(root) ==0 or root=='/':
            return self.get_drive_list()
        if model is None:
           return  [item for item in  os.listdir(root) if self._conmonfilter(item)] 
        elif model == "file":
            return [item for item in  os.listdir(root) if  os.path.isfile(os.path.join(root, item)) and self._conmonfilter(item)]
        else:
            return [item for item in  os.listdir(root) if  os.path.isdir(os.path.join(root, item)) and self._conmonfilter(item)]
    
    def do_rename(self,parent_dir ,old_list:list,new_list:list):
        for i in range(len(old_list)):
            old_name = os.path.join(parent_dir,old_list[i])
            new_name = os.path.join(parent_dir,new_list[i])
            os.rename(old_name,new_name)